<template>
  <div>
    <!-- 顶部操作栏 -->
    <div class="header-container">
      <span class="title">商品分类</span>
      <el-button
        type="primary"
        @click="handleAdd"
        style="margin-left: auto"
      >
        添加分类
      </el-button>
    </div>

    <!-- 分类表格 -->
    <el-table
      :data="tableData"
      style="width: 100%; margin-top: 20px"
    >
      <!-- 序号列 -->
      <el-table-column type="index" label="序号" width="80" />

      <el-table-column label="分类名称">
        <template #default="scope">
          <template v-if="isEditing(scope.row)">
            <el-input
              v-model="editingForm.cateName"
              placeholder="请输入分类名称"
              @keyup.enter="handleSave(scope.row)"
            />
          </template>
          <template v-else>
            {{ scope.row.cateName }}
          </template>
        </template>
      </el-table-column>

      <el-table-column label="是否启用">
        <template #default="scope">
          <el-switch
            :disabled="!isEditing(scope.row)"
            v-model="scope.row.state"
            active-color="#13ce66"
            inactive-color="#ff4949"
            @change="handleStateChange(scope.row)"
          />
        </template>
      </el-table-column>

      <el-table-column label="操作" width="240">
        <template #default="scope">
          <div v-if="isEditing(scope.row)" class="editing-controls">
            <el-button
              type="success"
              @click="handleSave(scope.row)"
              :loading="saving"
            >
              完成
            </el-button>
            <el-button @click="handleCancel(scope.row)" class="abc">删除</el-button>
          </div>
          <div v-else>
            <el-button
              type="primary"
              @click="handleEdit(scope.row)"
              :disabled="isEditing(scope.row)"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              style="background-color: #ffb6c1; border-color: #ffb6c1"
              @click="handleDelete(scope.row.id)"
              :disabled="isEditing(scope.row)"
            >
              删除
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 左侧分页控件 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[5, 10, 15, 20]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { catelist, delcate, editcate } from '@/views/api/goods.js';

const tableData = ref([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(5);
const editingRow = ref(null);
const originalData = ref(null);
const saving = ref(false);

const editingForm = reactive({
  id: '',
  cateName: '',
  state: null
});

// 检查是否正在编辑指定行
const isEditing = (row) => row.id === editingRow.value?.id;

// 获取分类列表
const getCateList = async () => {
  try {
    const res = await catelist({
      currentPage: currentPage.value,
      pageSize: pageSize.value
    });
    // 检查后端返回的数据结构
    if (res.total !== undefined && res.data !== undefined) {
      tableData.value = res.data.map(item => ({
        ...item,
        state: item.state === 1 // 将后端返回的 1 或 0 转换为布尔值
      }));
      total.value = res.total;
    } else {
      throw new Error('后端返回的数据结构不符合预期');
    }
  } catch (error) {
    ElMessage.error(`获取分类列表失败：${error.message}`);
    console.error('获取分类列表失败详情：', error);
  }
};

// 进入编辑模式
const handleEdit = (row) => {
  editingRow.value = row;
  originalData.value = { ...row };
  editingForm.id = row.id;
  editingForm.cateName = row.cateName;
  editingForm.state = row.state;
};

// 取消编辑
const handleCancel = (row) => {
  editingRow.value = null;
  // 恢复原始数据
  const index = tableData.value.findIndex(item => item.id === originalData.value.id);
  if (index !== -1) {
    tableData.value[index] = originalData.value;
  }
};

// 保存编辑
const handleSave = async (row) => {
  try {
    if (!editingForm.cateName.trim()) {
      ElMessage.warning('分类名称不能为空');
      return;
    }

    saving.value = true;
    // 直接使用布尔值发送到后端
    const params = {
      id: editingForm.id,
      cateName: editingForm.cateName,
      state: editingForm.state
    };

    const res = await editcate(params);
    if (res.code === 0) {
      ElMessage.success('保存成功');
      // 更新表格数据
      const index = tableData.value.findIndex(item => item.id === row.id);
      if (index !== -1) {
        tableData.value[index] = {
          ...tableData.value[index],
          cateName: editingForm.cateName,
          state: editingForm.state
        };
      }
      handleCancel(row);
    } else {
      ElMessage.error(res.msg || '保存失败');
    }
  } catch (error) {
    ElMessage.error('保存失败');
  } finally {
    saving.value = false;
  }
};

// 删除分类
const handleDelete = async (id) => {
  try {
    await ElMessageBox.confirm('确认删除该分类吗？', '提示', { type: 'warning' });
    const res = await delcate({ id });
    if (res.code === 0) {
      ElMessage.success('删除成功');
      getCateList();
    } else {
      ElMessage.error(res.msg || '删除失败');
    }
  } catch (error) {
    if (error !== 'cancel') ElMessage.error('删除失败');
  }
};

// 响应是否启用状态的改变
const handleStateChange = async (row) => {
  if (!isEditing(row)) {
    // 创建一个新的对象以避免直接修改原始数据
    const newRow = { ...row };
    editingRow.value = newRow;
    originalData.value = { ...row };
    editingForm.id = newRow.id;
    editingForm.cateName = newRow.cateName;
    editingForm.state = newRow.state;

    const params = {
      id: editingForm.id,
      cateName: editingForm.cateName,
      state: !editingForm.state // 切换状态
    };

    try {
      saving.value = true;
      const res = await editcate(params);
      if (res.code === 0) {
        ElMessage.success('状态更新成功');
        // 使用 Vue 的响应式 API 更新表格数据
        const index = tableData.value.findIndex(item => item.id === row.id);
        if (index !== -1) {
          tableData.value.splice(index, 1, {
            ...tableData.value[index],
            state: !editingForm.state
          });
        }
        handleCancel(newRow);
      } else {
        ElMessage.error(res.msg || '状态更新失败');
        // 恢复原始状态
        row.state = !row.state;
      }
    } catch (error) {
      ElMessage.error('状态更新失败');
      // 恢复原始状态
      row.state = !row.state;
    } finally {
      saving.value = false;
    }
  }
};

// 分页处理
const handleCurrentChange = (val) => {
  currentPage.value = val;
  getCateList();
};

const handleSizeChange = (val) => {
  pageSize.value = val;
  getCateList();
};

// 新增分类
const handleAdd = () => {
  editingRow.value = { id: 'new' };
  originalData.value = null;
  editingForm.id = '';
  editingForm.cateName = '';
  editingForm.state = true; // 默认启用
};

onMounted(getCateList);
</script>

<style scoped>
.header-container {
  padding: 20px;
  border-bottom: 2px solid #ccc;
  display: flex;
  align-items: center;
}

.title {
  font-size: 18px;
  font-weight: bold;
  margin-right: auto;
}

.pagination-container {
  margin-top: 20px;
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.editing-controls {
  display: flex;
  gap: 10px;
}

.el-input {
  width: 150px;
}

.el-button--danger {
  background-color: #ffb6c1;
  border-color: #ffb6c1;
}

.el-button--danger:hover {
  background-color: #ff9fa6;
}
.abc {
  background-color: #ffb6c1;
  border-color: #ffb6c1;
  color: #f5f7fa;
}
</style>